package com.shenzhen.horselive.api;

import com.google.gson.Gson;
import com.shenzhen.horselive.base.ActivityCollector;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.TokenOverTimeMessage;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class TokenInterceptor implements Interceptor {
    //token过期
    private static  final  String TOKEN_OVERTIME = "ERROR_TOKEN";
    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request originalRequest = chain.request();
        Response response = chain.proceed(originalRequest);
        try {

            ResponseBody responseBody = response.body();
            //解决response.body().string();只能打印一次
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();
            Charset UTF8 = Charset.forName("UTF-8");
            String string = buffer.clone().readString(UTF8);

            CommResponseBean baseResponseBean = new Gson().fromJson(string, CommResponseBean.class);
            if (baseResponseBean!=null)
            {
               if (baseResponseBean.getErrCode().equals(TOKEN_OVERTIME))
               {
                   //token过期
                   TokenOverTimeMessage  overTimeMessage=
                           new TokenOverTimeMessage();
                   overTimeMessage.setCode(0);
                   overTimeMessage.setMsg("登录过期");
                   EventBus.getDefault().post(overTimeMessage);
               }
            }


        }catch (Exception e)
        {

        }
        return response;
    }
}
